import lombok.extern.log4j.Log4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Log4j
public class RegistryCenter {
    private final ConcurrentHashMap<String, String> serviceRegistry = new ConcurrentHashMap<>();
    private static final ExecutorService SERVER_EXECUTOR = Executors.newFixedThreadPool(10); // 设置线程池大小为10个线程

    public void start(int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("注册中心启动，监听端口：" + port);
        log.info("注册中心启动，监听端口：" + port);
        while (true) {
            Socket socket = serverSocket.accept();
            SERVER_EXECUTOR.execute(() -> handleRequest(socket));
        }
    }

    private void handleRequest(Socket socket) {
        try (ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream())) {
            String serviceName = input.readUTF();
            String operation = input.readUTF();

            if ("register".equals(operation)) {
                String serviceAddress = input.readUTF();
                register(serviceName, serviceAddress);
                output.writeUTF("服务注册成功");
            } else if ("lookup".equals(operation)) {
                String address = lookup(serviceName);
                output.writeUTF(address != null ? address : "服务未找到");
            }
            output.flush();
        } catch (IOException e) {
            log.error("处理请求异常: " + e.getMessage());
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                log.error("关闭socket异常: " + e.getMessage());
            }
        }
    }

    public void register(String serviceName, String serviceAddress) {
        serviceRegistry.put(serviceName, serviceAddress);
    }

    public String lookup(String serviceName) {
        return serviceRegistry.get(serviceName);
    }

    public static void main(String[] args) throws IOException {
        ConfigLoader configLoader = new ConfigLoader("config.yml");
        new RegistryCenter().start(configLoader.getRegistryPort());
    }
}

